<template>
  <div class="app-container">
    <el-form :inline="true" ref="listQuery1" :model="listQuery" class="demo-form-inline" label-width="auto">
      <el-form-item prop="attachmentType" label="附件类型">
          <el-radio-group v-model="listQuery.attachmentType">
            <el-radio-button label="" key="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('AttachmentType')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="fileType" label="文件类型">
          <el-select v-model="listQuery.fileType" class="m-2" placeholder="请选择">
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in getDictList('FileType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item prop="md5" label="附件MD5值">
          <el-input v-model="listQuery.md5" placeholder="附件MD5值" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="fileName" label="名称">
          <el-input v-model="listQuery.fileName" placeholder="名称(关键词)" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="module" label="适用模块">
          <el-select v-model="listQuery.module" class="m-2" placeholder="请选择">
            <el-option key="" label="全部" value="" />
            <el-option v-for="item in getEnumList('Module')" :key="item.key" :label="item.value" :value="item.key" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <!-- <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button> -->
        </el-form-item>
    </el-form>
    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      row-key="id"
      fit
      tooltip-effect="dark"
      @sort-change="handleSortChange"
      @selection-change="handleSelectionChange"
      ref="multipleTable"
    >
      <el-table-column type="selection" width="39px" />
      <el-table-column label="文件名" prop="original" min-width="400px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <div :class="isPointer(row)" @dblclick.stop="enter(row)" title="双击进入该目录">
            <svg-icon :icon-class="getIconClassByFileName(row.fileName)" />
            <span v-if="row.attachmentType === '1'" style="font-weight: bold;">{{ row.fileName }}</span>
            <span v-if="row.attachmentType === '2'">{{ row.fileName }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="类型" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <span v-if="row.attachmentType === '1'">{{ showEnumLabel('AttachmentType', row.attachmentType) }}</span>
          <span v-if="row.attachmentType === '2'">{{ showDictLabel('FileType', row.fileType) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="大小" prop="fileSize" min-width="100px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ bytesToSize(row.fileSize) }}</template>
      </el-table-column>
      <el-table-column align="center" label="适用模块" prop="module" min-width="100px" show-overflow-tooltip>
        <template v-slot="{row}">{{ showEnumLabel('Module', row.module) }}</template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
    </el-table>
    <div style="text-align:right;margin: 1.875rem 0;">
      <el-button type="danger" @click="closeBtn">关闭</el-button>
      <el-button type="primary" @click="onSureBtn">确定</el-button>
    </div>
  </div>
</template>
<script setup>
import {ref, watch} from 'vue'
import {doGet} from "@/config/http";
import {
  alertErrorMsg,
  arrChangeTreeFn,
  bytesToSize,
  getDictList,
  getEnumList,
  getListPageSize, isNullOrUndefined, showDictLabel, showEnumLabel,
  svc
} from "@/config/common";
import {getUserId} from "@/config/cookie";

const props = defineProps({
  isVisible: {
    required: true,
    type: Boolean,
  },
})


let listQuery = ref({
  pageNum: 1,
  pageSize: getListPageSize(),
  sortField: 'id',
  sortType: 'desc',
  attachmentId: null,
  attachmentType: null,
  fileType: null,
  fileName: null,
  fileSize: null,
  downloads: null,
  references: null,
  uploader: getUserId(),
  uploaderName: null,
  module: null,
  parentId: null,
  createTimeStart: null,
  createTimeEnd: null,
  updateTimeStart: null,
  updateTimeEnd: null,
})

let listLoading = ref(true)
let total = ref(0)
let listRow = []
let list = ref([])
// let userList = ref([])
// let organizationList = ref([])
let directoryList = ref([])
let tableKey = ref(0)
let dirs = ref([])
let multipleTable = ref(null)
const emit = defineEmits(['close', 'selectAttachment'])

watch(() => props.isVisible, async val => {
  if (val) {
    toggleSelection()
  }
})

// 获取数据
const getList = () => {
  listLoading.value = true
  doGet(svc, '/customFile/findFileList', listQuery.value).then(res => {
    listLoading.value = false
    list.value = arrChangeTreeFn(res)
  }).catch(e => {
    console.error(e)
    listLoading = false
  })
}

const initList = async () => {
// let p1 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false)
// let p2 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false)
let p3 = doGet(svc, '/file/page', {attachmentType: "1", pageSize: getListPageSize()}, false)
let resArray = await Promise.all([p3])
// userList.value = resArray[0]['records']
// organizationList.value = resArray[1]['records']
directoryList.value = resArray[0]['records']
}

const handleFilter = () => {
  listQuery.value.pageNum = 1
  getList()
}

const isPointer = (row) => {
  return row.attachmentType === '1' ? 'pointer' : ''
}

const getIconClassByFileName = (name) => {
  if (name) {
    if (name.indexOf('.') <= 0) {
      return "dirs"
    }
    let suffix = name.split('.')[name.split('.').length - 1].toLowerCase()
    switch (suffix) {
      case "jpg":
      case "jpeg":
        return "jpg1"
      case "png":
        return "png1"
      case "pdf":
        return "pdf"
      case "xls":
      case "xlsx":
        return "excel1"
      case "doc":
      case "docx":
        return "word1"
      case "ppt":
      case "pptx":
        return "powerpoint1"
      case "mp3":
        return "mp3"
      case "mp4":
        return "mp4"
      case "avi":
        return "avi1"
      case "txt":
      case "text":
        return "txt"
      case "7z":
        return "7z"
      case "zip":
        return "zip"
      case "rar":
        return "rar"
      default:
        return "normal"
    }
  }
}

const enter = (row) => {
  if (isNullOrUndefined(row)) {
    listQuery.value.parentId = null
    dirs.value = []
    handleFilter()
    return
  }
  if (row.attachmentType !== '1') {
    return
  }
  listQuery.value.parentId = row.id
  handleFilter()
}

const handleSortChange = (data) => {
  const { prop, order } = data
  listQuery.value.sortField = prop
  listQuery.value.sortType = order === 'ascending' ? 'asc' : 'desc'
  handleFilter()
}

initList()
getList()

// 关闭弹层
function closeBtn() {
  emit('close')
}

// 清空选中
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach((row) => {
      multipleTable.value.toggleRowSelection(row, undefined)
    })
  } else {
    multipleTable.value.clearSelection()
  }
}

// 选择
function handleSelectionChange(val) {
  listRow = val.filter(item => item.attachmentType === '2')
}

// 点确定
function onSureBtn() {
  if (listRow.length === 0) {
    alertErrorMsg('请选择文件')
    return
  }
  emit('selectAttachment', listRow)
  emit('close')
}
</script>
<style>
.pagination-model {
  right: 36px !important;
}
</style>
